package com.zhx.qrcode.qrcode;

import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeGenWrapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class ZxingUtil {

    public static String createImage(String text, InputStream imgPath) throws Exception {
        HashMap map = new HashMap();
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//纠错程度
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        map.put(EncodeHintType.MARGIN, 1);//边框
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 300, 300, map);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        if (null == imgPath) {
            return imageToString(bufferedImage);
        }
        return null;
    }


    public static String imageToString(BufferedImage bufferedImage) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        return Base64.encodeBase64String(os.toByteArray());

    }


    public static String normal(String text) throws IOException, WriterException {
        return QrCodeGenWrapper.of(text).asString();
    }

    /**
     * https://www.w3school.com.cn/cssref/css_colors.asp  颜色大全网址
     * @param text
     * @return
     * @throws IOException
     * @throws WriterException
     */
    public static String color(String text) throws IOException, WriterException {
        return QrCodeGenWrapper.of(text).setDrawPreColor(Color.decode("#87CEEB")).asString();
    }


    public static void main(String[] args) throws IOException, WriterException {
        System.out.println(ZxingUtil.color("xxx"));
    }
}
